import api from "@/api/apiServer";
import { computeData } from "@/unit/tool";
import excel from "@/unit/lib/excel";
import XLSX from "xlsx";

import zh_CN from "ant-design-vue/lib/locale-provider/zh_CN";
import moment from "moment";
import "moment/locale/zh-cn";
moment.locale("zh-cn");
export const tableMinxins = {
  data() {
    return {
      locale: zh_CN,
      queryParam: {
        deleteFlag: "N",
      },
      /* 数据源 */
      tableData: [],
      /* 分页参数 */
      pagination: {
        current: 1,
        pageNumber: 1,
        pageSize: 10,
        showQuickJumper: false,
        showSizeChanger: false,
        showTotal: (total) => `共 ${total} 条`,
        total: 0,
      },
      labelCol: {
        xl: { span: 8 },
        xxl: { span: 8 },
      },
      wrapperCol: {
        xl: { span: 16 },
        xxl: { span: 16 },
      },
      deleteOption: [
        { value: "Y", label: "已删除" },
        { value: "N", label: "当前存在" },
      ],
      selectedKeys: [],
      /* table加载状态 */
      loading: false,
      /* table选中keys*/
      selectedRowKeys: [],
      /* table选中records*/
      selectionRows: [],
    };
  },

  created() {
    let queryParam = localStorage.getItem("queryParam");
    if (queryParam) {
      this.queryParam = JSON.parse(queryParam);
    }
  },
  mounted() {
    window.addEventListener("keydown", this.KeyDown, true); // 监听按键事件
  },
  beforeDestroy() {
    window.addEventListener("keydown", this.KeyDown, false); // 监听按键事件
  },
  computed: {},
  methods: {
    // 获取查询条件
    getQueryParams() {
      let sqp = {};
      sqp.pageNumber = this.pagination.current;
      sqp.pageSize = this.pagination.pageSize;
      var param = Object.assign(sqp, this.queryParam);
      return this.filterObj(param);
    },
    // 查询全部数据
    async handleAllList(key) {
      this.pagination.current = 1;
      this.pagination.pageNumber = 1;
      this.pagination.pageSize = 10;
      this.queryParam = {};
      this.selectedKeys = [];
      this.$set(this.queryParam, "deleteFlag", "N");
      this.getList();
    },
    handleSearch(key) {
      if (typeof key == "string") {
        this.queryParam[key] = "";
        this.selectedKeys = [];
      }
      this.pagination.current = 1;
      this.getList();
    },
    modalFormOk() {
      this.queryParam = {};
      this.$set(this.queryParam, "deleteFlag", "N");
      this.selectedKeys = [];
      // 新增/修改 成功时，重载列表
      this.getList();
      //清空列表选中
      this.onClearSelected();
    },
    onClearSelected() {
      this.selectedRowKeys = [];
      this.selectionRows = [];
    },
    // 绑定键盘快捷键
    KeyDown(event) {
      if (event.keyCode === 112) {
        event.returnValue = false;
        this.handleAdd(); //触发全屏的按钮
      }

      // else if (event.keyCode === 117) {
      //   event.returnValue = false;
      //   this.getList(); //触发全屏的按钮
      // }
    },
    // 新增
    handleAdd() {
      this.$refs.modalForm.title = "新增";
      this.$refs.modalForm.modalAdd();
    },
    //  编辑
    handleEdit(record) {
      this.$refs.modalForm.title = "编辑";
      this.$refs.modalForm.modalEdit(record);
    },
    // 分页、排序、筛选变化时触发
    handleTableChange(pagination, filters, sorter) {
      this.pagination = pagination;
      this.getList();
    },
    // 过滤对象中为空的属性
    filterObj(obj) {
      if (!(typeof obj == "object")) {
        return;
      }
      for (let key in obj) {
        if (
          obj.hasOwnProperty(key) &&
          (obj[key] == null || obj[key] == undefined || obj[key] === "")
        ) {
          delete obj[key];
        }
      }
      return obj;
    },
    // 路由跳转
    handleJump(path) {
      this.$router.push({ path });
    },
    // 导出导入模板
    handelExportTemplate(filename, columns) {
      let title = [];
      let key = [];
      columns.forEach((item) => {
        if (item.dataIndex !== "action" && item.dataIndex !== "index") {
          title.push(item.title);
          key.push(item.dataIndex);
        }
      });
      const params = {
        title,
        key,
        data: [],
        autoWidth: true,
        filename,
      };
      excel.export_array_to_excel(params);
    },
    // 列表导出方法
    async handelExport(filename, keyName, columns) {
      let title = [];
      let key = [];
      columns.forEach((item) => {
        if (item.dataIndex !== "action" && item.dataIndex !== "index") {
          title.push(item.title);
          key.push(item.dataIndex);
        }
      });

      let data = await this.getDownloadData(keyName);
      const params = {
        title,
        key,
        data,
        autoWidth: true,
        filename,
      };
      excel.export_array_to_excel(params);
    },
    // 导出总数据查询
    async getDownloadData(keyName) {
      // 数据总条数
      let total = this.pagination.total;
      // 单条数据大小
      let SingleSize = computeData(this.tableData[0]);
      // 限制总大小
      let main = 20 * 1024 * 1024;
      // 可导出数量
      let num = Math.ceil(main / SingleSize);
      // 最大总页数
      let pageSize = 300;
      // 可导出总条数
      let MaxLength = Math.ceil(num / pageSize);
      // 当前条数
      let length = 0;
      // 判断当前后台接口返回的条数
      if (total > num) {
        length = MaxLength;
      } else {
        length = Math.ceil(total / pageSize);
      }
      // 最后导出的数据
      let newLists = [];
      for (let i = 1; i <= length; i++) {
        let lists = await this.getDataList(
          {
            pageNumber: i,
            pageSize: pageSize,
          },
          keyName
        );
        newLists.push(lists);
      }
      return [].concat(...newLists);
    },
    // 导出时获取只分页的数据
    async getDataList(params, keyName) {
      const res = await api[keyName](params);
      if (!res.data.total) {
        return [];
      } else {
        return res.data.data;
      }
    },

    // 导入
    handelImport() {
      this.$refs.fileTemp.click(); // 浏览文件
    },
    getImportFile() {
      if (this.$refs.fileTemp && !this.$refs.fileTemp.files[0]) return false;
      const selectedFile = this.$refs.fileTemp.files[0];

      this.readFile(selectedFile);
    },
    readFile(file) {
      let that = this;
      let reader = new FileReader();
      reader.onload = function(e) {
        let wb = XLSX.read(e.target.result, { type: "binary" }); // 读取文件
        let wbSheetName = wb.SheetNames[0];
        const wbSheet = wb.Sheets[wbSheetName];
        // 解析文件 {defval: ''}=>防止单元格为空的时解析出来的结果缺少相应的key
        let selectFileData = XLSX.utils.sheet_to_json(wbSheet, { defval: "" });
        if (!selectFileData.length) {
          console.log(`上传的文件数据为空！`);
          return false;
        } else {
          // console.log(selectFileData);
        }
        // console.log(selectFileData);

        let title = [];
        let key = [];
        that.columns.forEach((item) => {
          if (item.dataIndex !== "action" && item.dataIndex !== "index") {
            title.push(item.title);
            key.push(item.dataIndex);
          }
        });
        let newArr = that.convertKey(selectFileData, key);
        that.setImport(newArr);
      };
      reader.readAsBinaryString(file);
    },

    convertKey(arr, key) {
      let dataNew = []; //新数组
      arr.forEach((item, index) => {
        let obj = {}; //新数组里的新对象
        for (var i = 0; i < key.length; i++) {
          obj[key[i]] = item[Object.keys(item)[i]]; //key值替换
        }
        dataNew.push(obj);
      });
      return dataNew;
    },
  },
};
